package com.dk.shiro;



import com.dk.pojo.User;
import com.dk.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//自定义Realm类

public class UserRealm extends AuthorizingRealm {

   @Autowired
   private IUserService iUserService;

//    执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

//    执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
//        获取 封装了表单提交信息的 token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = iUserService.slectUserByUsername(token.getUsername());
//       根据用户名查询数据库数据
//       判断用户是否存在
       if (user == null){
          return null; //return null 底层会抛出用户不存在异常到Controller
       }
//       判断用户是否正常 Y正常  N异常
//        String status = user.getStatus();
//        if (!"Y".equals(status)){
//            throw new LoginException();
//        }
//      判断密码  参数1: 实体类,登录成功自动存到域对象; 参数2: 数据库密码 参数3:根据用户数据库加密的盐值进行加密 参数4: 用户的真实姓名
        return new SimpleAuthenticationInfo(user,user.getPassword(), user.getUname()); // 底层自动校验密码
    }
}
